// ignore_for_file: use_build_context_synchronously
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xvideos/assets_tool/images.dart';
import 'package:xvideos/hj_model/video_model.dart';
import 'package:xvideos/hj_page/mine_business/collec_history_buy/col_his_buy_sub_page.dart';
import 'package:xvideos/hj_page/short_video/view/right_menu/video_load_button.dart';
import 'package:xvideos/hj_utils/api_service/acg_service.dart';
import 'package:xvideos/hj_utils/api_service/common_service.dart';
import 'package:xvideos/hj_utils/api_service/mine_service.dart';
import 'package:xvideos/hj_utils/global.dart';
import 'package:xvideos/hj_utils/widget_utils.dart';
import 'package:like_button/like_button.dart';
import 'package:video_player/video_player.dart';

import '../../../alert_business/video/share_video_dialog.dart';
import '../../../alert_business/video/video_line_menu_alert.dart';

class VideoDetailBottomMenu extends StatefulWidget {
  final VideoModel? model;
  final VideoPlayerController? controller;
  final Function? callback;
  final String? typeValue; // 短视频 short， 文章 cover, 长视频 movie
  const VideoDetailBottomMenu({
    super.key,
    this.model,
    this.callback,
    this.controller,
    this.typeValue,
  });

  @override
  State<StatefulWidget> createState() {
    return _VideoDetailBottomMenuState();
  }
}

class _VideoDetailBottomMenuState extends State<VideoDetailBottomMenu> {
  VideoModel? get videoModel => widget.model;

  bool get isLike => videoModel?.vidStatus?.hasLiked ?? false;

  bool get isCollect => videoModel?.vidStatus?.hasCollected ?? false;

  bool get isCartoon => videoModel?.mediaInfo != null;

  @override
  void initState() {
    super.initState();
  }

  Future<bool> _onLikeEvent() async {
    bool preLike = isLike;
    if (isLike) {
      await CommonService.cancelLike(videoModel?.id, isCartoon ? "video" : "SP");
    } else {
      await CommonService.sendLike(videoModel?.id, isCartoon ? "video" : "SP");
    }

    videoModel?.vidStatus?.hasLiked = !isLike;
    if (preLike) {
      int count = videoModel?.likeCount ?? 1;
      videoModel?.likeCount = count - 1;
    } else {
      int count = videoModel?.likeCount ?? 0;
      videoModel?.likeCount = count + 1;
    }
    setState(() {});
    return videoModel?.vidStatus?.hasLiked ?? false;
  }

  void _onShareEvent() async {
    Get.dialog(ShareVideoDialog(videoModel: videoModel, isCoverV: isCartoon));
  }

  Future<bool> _onCollectEvent() async {
    bool preCollect = isCollect;
    if (isCartoon) {
      if (preCollect) {
        await ACGService.mediaBookshelfDelete(videoModel?.id ?? "");
      } else {
        await ACGService.mediaBookshelfAdd(videoModel?.id ?? "");
      }
    } else {
      await MineService.postCollect(videoModel?.id, "SP", !isCollect);
    }
    if (!preCollect) {
      videoModel?.collectCount = (videoModel?.collectCount ?? 0) + 1;
    } else {
      videoModel?.collectCount = (videoModel?.collectCount ?? 1) - 1;
    }
    videoModel?.vidStatus?.hasCollected = !isCollect;
    videoModel?.mediaInfo?.mediaStatus?.hasCollected = !isCollect;
    videoModel?.mediaInfo?.countCollect = videoModel?.collectCount;

    if (!preCollect) {
      showToast("收藏成功");
    } else {
      showToast("取消收藏成功");
    }
    setState(() {});

    return videoModel?.vidStatus?.hasCollected ?? false;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Row(
        children: <Widget>[
          Expanded(
            child: Text(
              "${videoModel?.playCount?.humanizeFormat ?? ""} 观看量",
              style: TextStyle(
                color: Color(0xff989898),
                fontSize: 12,
              ),
            ),
          ),

          /// 喜欢
          _buildLikeBtn(videoModel?.likeCount?.humanizeFormatDefault("点赞") ?? "点赞"),
          12.sizeBoxW,

          /// 收藏
          _buildCollectItem(),
          12.sizeBoxW,

          /// 分享
          _buildShareItem(1, "分享", "share_path.png".videoPath),
          12.sizeBoxW,

          /// 下载
          VideoLoadButton(
            key: ValueKey(videoModel?.id),
            videoModel: videoModel,
            isShort: false,
          ),
        ],
      ),
    );
  }

  Widget _buildCollectItem() {
    return GestureDetector(
      onTap: _onCollectEvent,
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Image.asset(
            isCollect ? 'collect_red.png'.commonImgPath : 'collect_grey.png'.commonImgPath,
            width: 14,
          ),
          2.sizeBoxW,
          Container(
            child: Text(
              videoModel?.collectCount.humanizeFormatDefault(isCartoon ? '收藏' : '收藏') ?? (isCartoon ? '收藏' : '收藏'),
              style: TextStyle(
                color: Color(0xff989898),
                fontSize: 10,
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget _buildShareItem(int index, String? title, String imagePath) {
    return InkWell(
      onTap: () {
        _onShareEvent();
      },
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Image.asset(
            imagePath,
            width: 14,
            height: 14,
          ),
          2.sizeBoxW,
          Text(
            title ?? "",
            style: TextStyle(
              color: Color(0xff989898),
              fontSize: 10,
            ),
          ),
        ],
      ),
    );
  }

  _buildLikeBtn(String? title) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        LikeButton(
          isLiked: isLike,
          size: 16,
          likeBuilder: (isLiked) => Image.asset(
            isLiked ? "video_liked.png".videoPath : "video_like_grey.webp".videoPath,
          ),
          onTap: (isLiked) => _onLikeEvent(),
        ),
        2.sizeBoxW,
        Container(
          padding: EdgeInsets.only(right: 3),
          child: Text(
            title ?? "",
            style: TextStyle(
              color: Color(0xff989898),
              fontSize: 10,
            ),
          ),
        ),
      ],
    );
  }
}
